﻿' --- Copyright (c) notice NevoWeb ---
'  Copyright (c) 2008 SARL NevoWeb.  www.nevoweb.com. All rights are reserved.
' Author: D.C.Lee
' ------------------------------------------------------------------------
' THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
' TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
' THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
' CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
' DEALINGS IN THE SOFTWARE.
' ------------------------------------------------------------------------
' This copyright notice may NOT be removed, obscured or modified without written consent from the author.
' --- End copyright notice --- 


Imports System
Imports System.Web
Imports System.Net
Imports System.IO
Imports NEvoWeb.Modules.NB_Store.SharedFunctions
Imports System.Collections.Specialized

Namespace NEvoWeb.Modules.NB_Store.Gateway

    Public Class GatewayPxPay
        Inherits GatewayInterface

        Public Overrides Function GetButtonHtml(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String) As String
            'This function simple displays a image buuton that can be clicked to select the type of payment.
            Dim strHTML As String = ""
            Dim objSCtrl As New SettingsController
            Dim objSInfo As NB_Store_SettingsInfo
            objSInfo = objSCtrl.GetSetting(PortalID, "PxPay.gateway", Lang)

            If Not objSInfo Is Nothing Then
                Dim setParams As Hashtable = createSettingsTable(objSInfo.SettingValue)

                strHTML = "<INPUT TYPE=IMAGE NAME=PXPAY BORDER=0 SRC=""" & setParams("ButtonImageURL") & """/>"

            End If

            Return strHTML
        End Function


        Public Overrides Sub AutoResponse(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest)
            ' This is not used by PxPay, as the autoresponse uses the same url as return url. (stg/5)
            'redirect to getcompleted.
            GetCompletedHtml(PortalID, -1, Request)
        End Sub

        Public Overrides Function GetCompletedHtml(ByVal PortalID As Integer, ByVal UserID As Integer, ByVal Request As System.Web.HttpRequest) As String
            Try
                UpdateLog("AUTO ---- START -------")

                Dim objSCtrl As New SettingsController
                Dim objOCtrl As New OrderController
                Dim objPCtrl As New ProductController
                Dim objOInfo As NB_Store_OrdersInfo
                Dim objSTInfo As NB_Store_SettingsTextInfo
                Dim objSInfo As NB_Store_SettingsInfo
                Dim ordID As String = ""
                Dim rtnMsg As String = ""
                Dim ResultQs As String = ""
                Dim output As ResponseOutput = Nothing
                Dim language As String = ""

                'get authorization, if exists
                If Not Request.QueryString("result") Is Nothing Then
                    ResultQs = Request.QueryString("result")
                End If

                objSInfo = objSCtrl.GetSetting(PortalID, "PXPAY.gateway", "None")
                If ResultQs <> "" And Not objSInfo Is Nothing Then

                    Dim setParams As Hashtable = createSettingsTable(objSInfo.SettingValue)

                    Dim PxPayUserId As String = setParams("PxPayUserId")
                    Dim PxPayKey As String = setParams("PxPayKey")


                    ' Obtain the transaction result 
                    Dim WS As New PxPay(PxPayUserId, PxPayKey, setParams("PaymentExpress.PxPay"))

                    output = WS.ProcessResponse(ResultQs)

                    ordID = output.TxnData1
                    language = output.TxnData2

                End If


                'set rtnMsg to security error message
                objSTInfo = objSCtrl.GetSettingsText(PortalID, "paymentSECURITY.text", GetCurrentCulture)
                rtnMsg = objSTInfo.SettingText
                If IsNumeric(ordID) Then
                    objOInfo = objOCtrl.GetOrder(CInt(ordID))
                    If Not objOInfo Is Nothing Then
                        Select Case UCase(Request.QueryString("PxPayExit"))
                            Case "CANCEL"
                                UpdateLog("PxPay GetCompletedHtml CANCELLED orderid=" & ordID)
                                ' check if order has already been processed
                                If Not objOInfo.OrderIsPlaced Then
                                    'check if order has already been cancelled
                                    If Not objOInfo.OrderStatusID = 30 Then
                                        'remove qty in trans
                                        objPCtrl.RemoveModelQtyTrans(objOInfo.OrderID)
                                        'set order status to cancelled
                                        objOInfo.OrderStatusID = 30
                                        objOCtrl.UpdateObjOrder(objOInfo)
                                    End If
                                    'set Cancel order message
                                    objSTInfo = objSCtrl.GetSettingsText(PortalID, "paymentFAIL.text", GetCurrentCulture)
                                    rtnMsg = objSTInfo.SettingText

                                End If
                            Case "RETURN"
                                If UserID < 0 Then
                                    UpdateLog("PxPay GetCompletedHtml AUTO OK: orderid=" & ordID)
                                Else
                                    UpdateLog("PxPay GetCompletedHtml RETURN OK: orderid=" & ordID)
                                End If
                                ' check if order has already been processed
                                If Not objOInfo.OrderIsPlaced And Not objOInfo.OrderStatusID = 30 Then
                                    'remove qty in trans
                                    objOInfo.OrderIsPlaced = True
                                    objOCtrl.UpdateObjOrder(objOInfo)

                                    Dim objMInfo As NB_Store_ModelInfo
                                    Dim aryList As ArrayList

                                    aryList = objOCtrl.GetOrderDetailList(ordID)
                                    For Each obj As NB_Store_OrderDetailsInfo In aryList
                                        objMInfo = objPCtrl.GetModel(obj.ModelID, GetCurrentCulture)
                                        UpdateLog("AUTO BF Stock Upd: orderid=" & ordID.ToString & " QtyRemaining=" & objMInfo.QtyRemaining & " QtyTrans=" & objMInfo.QtyTrans & " QtyTransDate=" & objMInfo.QtyTransDate)
                                    Next

                                    objPCtrl.UpdateStockLevel(objOInfo.OrderID)

                                    aryList = objOCtrl.GetOrderDetailList(ordID)
                                    For Each obj As NB_Store_OrderDetailsInfo In aryList
                                        objMInfo = objPCtrl.GetModel(obj.ModelID, GetCurrentCulture)
                                        UpdateLog("AUTO AF Stock Upd: orderid=" & ordID.ToString & " QtyRemaining=" & objMInfo.QtyRemaining & " QtyTrans=" & objMInfo.QtyTrans & " QtyTransDate=" & objMInfo.QtyTransDate)
                                    Next

                                    'set order status to Payed
                                    objOInfo.OrderStatusID = 40
                                    If objOInfo.UserID = -1 Then
                                        objOInfo.OrderNumber = Format(PortalID, "00") & "-00000-" & objOInfo.OrderID.ToString("0000#") & "-" & objOInfo.OrderDate.ToString("yyyyMMdd")
                                    Else
                                        objOInfo.OrderNumber = Format(PortalID, "00") & "-" & objOInfo.UserID.ToString("0000#") & "-" & objOInfo.OrderID.ToString("0000#") & "-" & objOInfo.OrderDate.ToString("yyyyMMdd")
                                    End If

                                    objOCtrl.UpdateObjOrder(objOInfo)

                                    SendEmailToClient(PortalID, GetClientEmail(PortalID, objOInfo), objOInfo.OrderNumber, objOInfo, "paymentOK.email", language)
                                    SendEmailToManager(PortalID, objOInfo.OrderNumber, objOInfo, "paymentOK.email")
                                End If
                                'set completed order message
                                objSTInfo = objSCtrl.GetSettingsText(PortalID, "paymentOK.text", GetCurrentCulture)
                                rtnMsg = objSTInfo.SettingText

                            Case Else
                                ' break
                        End Select

                        UpdateLog("AUTO ---- END -------")

                        'Do Token Replacement
                        Dim objTR As New TokenStoreReplace(objOInfo, GetMerchantCulture(PortalID))
                        rtnMsg = objTR.DoTokenReplace(rtnMsg)
                    End If
                End If
                Return rtnMsg
            Catch ex As Exception
                SendEmailToAdministrator(PortalID, "ERROR on Return (or AutoReponse) PxPay Portal:" & PortalID.ToString, ex.ToString)
                UpdateLog("ERROR on Return (or AutoReponse) PxPay Portal:" & PortalID.ToString & " = " & ex.ToString)
                Return ""
            End Try
        End Function

        Public Overrides Function GetBankClick(ByVal PortalID As Integer, ByVal Request As System.Web.HttpRequest) As Boolean
            'test if PXPAY button has been clicked
            If Not Request.Form.Item("PXPAY.x") Is Nothing Then
                Return True
            Else
                Return False
            End If
        End Function

        Public Overrides Sub SetBankRemotePost(ByVal PortalID As Integer, ByVal OrderID As Integer, ByVal Lang As String, ByVal Request As System.Web.HttpRequest)

            Dim RPost As New RemotePost

            'test if e-way button has been clicked
            If Not Request.Form.Item("PXPAY.x") Is Nothing Then
                Dim objSCtrl As New SettingsController
                Dim objSInfo As NB_Store_SettingsInfo
                objSInfo = objSCtrl.GetSetting(PortalID, "PXPAY.gateway", "None")
                If Not objSInfo Is Nothing Then

                    Dim setParams As Hashtable = createSettingsTable(objSInfo.SettingValue)

                    Dim objOCtrl As New OrderController
                    Dim oInfo As NB_Store_OrdersInfo = objOCtrl.GetOrder(OrderID)

                    If Not oInfo Is Nothing Then

                        'update stock tranction in progress
                        Dim objPCtrl As New ProductController
                        objPCtrl.UpdateModelQtyTrans(oInfo.OrderID)

                        'set order status to redirect to bank
                        oInfo.OrderStatusID = 20
                        objOCtrl.UpdateObjOrder(oInfo)

                        Dim LoadingImg As String = ""
                        Dim PurgeOrderMins As Double = -1
                        Dim TimeOut As String = ""
                        objSInfo = objSCtrl.GetSetting(PortalID, "gateway.loadimage", "None")
                        If Not objSInfo Is Nothing Then
                            LoadingImg = objSInfo.SettingValue
                        End If
                        objSInfo = objSCtrl.GetSetting(PortalID, "gatewayexpiremins", "None")
                        If Not objSInfo Is Nothing Then
                            If IsNumeric(objSInfo.SettingValue) Then
                                PurgeOrderMins = objSInfo.SettingValue
                                Dim ExpireDate As Date
                                ExpireDate = DateAdd(DateInterval.Minute, PurgeOrderMins, DateTime.UtcNow)
                                oInfo.OrderDate = Now
                                objOCtrl.UpdateObjOrder(oInfo)
                                TimeOut = Right(Year(ExpireDate).ToString("0000"), 2) & Month(ExpireDate).ToString("00") & Day(ExpireDate).ToString("00") & Hour(ExpireDate).ToString("00") & Minute(ExpireDate).ToString("00")
                            End If
                        End If


                        '---------------------------------------------
                        ' Do PxPay processing
                        '---------------------------------------------


                        Dim PxPayUserId As String = setParams("PxPayUserId")
                        Dim PxPayKey As String = setParams("PxPayKey")

                        Dim WS As New PxPay(PxPayUserId, PxPayKey, setParams("PaymentExpress.PxPay"))

                        Dim input As New RequestInput()

                        input.AmountInput = oInfo.Total.ToString("0.00")
                        input.CurrencyInput = setParams("InputCurrency")
                        input.MerchantReference = replace(setParams("MerchantReference"),"[ORDERID]",oInfo.OrderID.ToString)
                        input.TxnType = setParams("TxnType")
                        input.UrlFail = setParams("ReturnCancelURL")
                        input.UrlSuccess = setParams("ReturnURL")
                        input.TxnData1 = oInfo.OrderID
                        input.TxnData2 = Lang
                        input.TxnId = oInfo.OrderID.ToString & Year(Today).ToString & Month(Today).ToString & Day(Today).ToString
                        input.Opt = ""
                        If TimeOut <> "" Then
                            input.Opt = "TO=" & TimeOut
                        End If

                        UpdateLog("PXPAY DATA = " & input.TxnId & " : " & input.Opt.ToString)

                        Dim output As RequestOutput = WS.GenerateRequest(input)

                        If output.valid = "1" Then

                            RPost = New RemotePost

                            RPost.Url = output.Url

                            ' Redirect user to payment page 
                            Dim objCInfo As NB_Store_CartInfo = CurrentCart.GetCurrentCart(PortalID)
                            objCInfo.BankHtmlRedirect = RPost.GetPostHtml(LoadingImg)
                            objCInfo.DateCreated = DateAdd(DateInterval.Minute, 5, Now)
                            CurrentCart.Save(objCInfo)

                        End If

                        '---------------------------------------------

                    End If
                End If
            End If
        End Sub

        Public Function createSettingsTable(ByVal SettingsParams As String) As Hashtable
            Return ParseGateway(SettingsParams)
        End Function

    End Class





End Namespace

